package com.bluesky.android.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import net.robotmedia.acv.Constants;
import net.robotmedia.acv.logic.TrackingManager;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class MangaUtility {
	public static final String MANGA_LOG_TAG = "MangaLogtag";
	public static String saveBitmapToDisk(String filePath, Bitmap bitmap) {
		FileOutputStream out = null;
		try {
			File file = new File(filePath);
			out = new FileOutputStream(file);
			boolean success = bitmap.compress(CompressFormat.JPEG, Constants.COMPRESSION_QUALITY, out);
			out.close();
			if (success) {
				return file.getPath();
			}
		} catch (Exception e) {
			e.printStackTrace();
			TrackingManager.trackError("Comic.saveBitmap", e);
			if (out != null) {
				try { out.close(); } catch (Exception e1) {}
			}
		} finally {
			bitmap = null;
		}
		return null;
	}
	public static Bitmap GetImageFromURL(String url){
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}
	public static String unescape (String s)
	{
		if(s!= null){
			 while (true)
			    {
			        int n=s.indexOf("&#");
			        if (n<0) break;
			        int m=s.indexOf(";",n+2);
			        if (m<0) break;
			        try
			        {
			            s=s.substring(0,n)+(char)(Integer.parseInt(s.substring(n+2,m)))+
			                s.substring(m+1);
			        }
			        catch (Exception e)
			        {
			            return s;
			        }
			    }
			    s=s.replace("&quot;","\"");
			    s=s.replace("&lt;","<");
			    s=s.replace("&gt;",">");
			    s=s.replace("&amp;","&");
			    s= s.replace("&nbsp;", " ");
			    return s;
		}
		return "";
	}
	public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int
			dstHeight, ScalingLogic scalingLogic) { 
		Bitmap scaledBitmap = null;
		try{
			Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight, scalingLogic); 
			Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), 
			unscaledBitmap.getHeight(), dstWidth, dstHeight, scalingLogic); 
			scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(), 
					Config.ARGB_8888); 
			Canvas canvas = new Canvas(scaledBitmap); 
			canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG)); 
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return scaledBitmap; 
	}
	public static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int 
			dstHeight, ScalingLogic scalingLogic) { 
			    if (scalingLogic == ScalingLogic.CROP) { 
			        final float srcAspect = (float)srcWidth / (float)srcHeight; 
			        final float dstAspect = (float)dstWidth / (float)dstHeight; 
			 
			        if (srcAspect > dstAspect) { 
			            final int srcRectWidth = (int)(srcHeight * dstAspect); 
			            final int srcRectLeft = (srcWidth - srcRectWidth) / 2; 
			            return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight); 
			        } else { 
			            final int srcRectHeight = (int)(srcWidth / dstAspect); 
			            final int scrRectTop = (int)(srcHeight - srcRectHeight) / 2; 
			            return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight); 
			        } 
			    } else { 
			        return new Rect(0, 0, srcWidth, srcHeight); 
			    } 
			} 
			 
		public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int 
			dstHeight, ScalingLogic scalingLogic) { 
			    if (scalingLogic == ScalingLogic.FIT) { 
			        final float srcAspect = (float)srcWidth / (float)srcHeight; 
			        final float dstAspect = (float)dstWidth / (float)dstHeight; 
			 
			        if (srcAspect > dstAspect) { 
			            return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect)); 
			        } else { 
			            return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight); 
			        } 
			    } else { 
			        return new Rect(0, 0, dstWidth, dstHeight); 
			    } 
			} 
		public static Bitmap decodeFile(String pathName, int dstWidth, int dstHeight, 
				ScalingLogic scalingLogic) { 
				    Options options = new Options(); 
				    options.inJustDecodeBounds = true; 
				    BitmapFactory.decodeFile(pathName, options); 
				    options.inJustDecodeBounds = false; 
				    options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, 
				dstWidth, dstHeight, scalingLogic); 
				    Bitmap unscaledBitmap = BitmapFactory.decodeFile(pathName, options); 
				 
				    return unscaledBitmap; 
		} 
				 
		public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int 
				dstHeight, ScalingLogic scalingLogic) { 
				    if (scalingLogic == ScalingLogic.FIT) { 
				        final float srcAspect = (float)srcWidth / (float)srcHeight; 
				        final float dstAspect = (float)dstWidth / (float)dstHeight; 
				 
				        if (srcAspect > dstAspect) { 
				            return srcWidth / dstWidth; 
				        } else { 
				            return srcHeight / dstHeight; 
				        } 
				    } else { 
				        final float srcAspect = (float)srcWidth / (float)srcHeight; 
				        final float dstAspect = (float)dstWidth / (float)dstHeight; 
				 
				        if (srcAspect > dstAspect) { 
				            return srcHeight / dstHeight; 
				        } else { 
				            return srcWidth / dstWidth; 
				        } 
				    } 
				} 
		public static String md5(String s) {
		    try {
		        // Create MD5 Hash
		        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
		        digest.update(s.getBytes());
		        byte messageDigest[] = digest.digest();
		        
		        // Create Hex String
		        StringBuffer hexString = new StringBuffer();
		        for (int i=0; i<messageDigest.length; i++)
		            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
		        return hexString.toString();
		        
		    } catch (NoSuchAlgorithmException e) {
		        e.printStackTrace();
		    }
		    return "";
		}
}
